package com.liaogui.算法题;

import java.util.HashMap;

/**
 *
 * @author liaogui
 * @date 2025/3/31 21:41
 */
public class 两数只和 {
    public static void main(String[] args) {
        twoSumByMap(new int[] {1, 2, 3}, 4);
    }

    public static int[] twoSum(int[] nums, int target) {
        int[] s = new int[2];
        for(int i=0;i< nums.length; i++) {
            for(int j = i+1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target) {
                    return new int[]{i, j};                }
            }
        }
        throw new RuntimeException("找不到结果");
    }

    public static int[] twoSumByMap(int[] nums, int target) {
        int length = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < length; i++) {
            if (map.containsKey(target - nums[i])) {
                return new int[]{map.get(target - nums[i]), i};
            }
            map.put(nums[i], i);
        }
        throw new RuntimeException("找不到结果");
    }
}
